﻿using AutoMapper;
using MediatR;
using S.Common.ApiResult;
using S.Transplantation.Domain.Models;
using S.Transplantation.Infrastructure.InterFace;
using S.Transplantation.Read.Api.Application.Command;
using S.Transplantation.Read.Api.Dto;
using System.Linq;

namespace S.Transplantation.Read.Api.Application.CommandHandlers
{
    public class TransplantationCommandHandler :
        IRequestHandler<GetTransplantationListCommand, ApiResult<List<GetTransplantationListDto>>>,IRequestHandler<BackfillTransplantationCommand, DescendantTransferModel>
    {
        private readonly IDescendantTransfertRepository DTRepository;
        private readonly IMapper mapper;

        public TransplantationCommandHandler(IDescendantTransfertRepository DTRepository, IMapper mapper)
        {
            this.DTRepository = DTRepository;
            this.mapper = mapper;
        }

        public async Task<ApiResult<List<GetTransplantationListDto>>> Handle(GetTransplantationListCommand request, CancellationToken cancellationToken)
        {
            ApiResult<List<GetTransplantationListDto>> result = new ApiResult<List<GetTransplantationListDto>>();
            var DT = DTRepository.GetAll();
            result.totalCount = DT.Count();
            if (!string.IsNullOrEmpty(request.EarTag))
            {
                DT = DT.Where(a => a.EarTag.Contains(request.EarTag));
            }

            if (!string.IsNullOrEmpty(request.BeginTime))
            {
                DT = DT.Where(a => a.TransferDate >= Convert.ToDateTime(request.BeginTime));
            }

            if (!string.IsNullOrEmpty(request.EndTime))
            {
                DT = DT.Where(a => a.TransferDate <= Convert.ToDateTime(request.EndTime));
            }
            DT = DT.OrderByDescending(a => a.CreateDate);
            DT = DT.Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize);

            var list = mapper.Map<List<GetTransplantationListDto>>(DT);

            result.Data = list;

            return result;
        }
        /// <summary>
        /// 反填转种信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<DescendantTransferModel> Handle(BackfillTransplantationCommand request, CancellationToken cancellationToken)
        {
            var data=  DTRepository.GetAll().FirstOrDefault(x=>x.DescendantTransferId==request.Id);
            return data;
        }
    }
}